package com.zdp.filesync.commonline.entity;


import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.stream.Collectors;

public class StreamGobbler implements Callable<Object> {

    private InputStream inputStream;

    // 是否返回原始结果
    private boolean isOrigin = true;
    private Function<String,Boolean> function;

    private String charset = "UTF-8";

    public void setCharset(String charset){
        if(!StringUtils.isBlank(charset)){
            this.charset = charset;
        }
    }

    public StreamGobbler(InputStream inputStream){
        this.inputStream = inputStream;
        this.isOrigin = true;
    }

    public StreamGobbler(InputStream inputStream,Function<String,Boolean> function){
        this(inputStream);
        this.function = function;
        this.isOrigin = false;
    }


    @Override
    public Object call() throws Exception {
        if(isOrigin){
            String result = new BufferedReader(new InputStreamReader(inputStream,charset)).lines()
                    .collect(Collectors.joining("\n"));
            return result;
        }else{
            // 返回执行结果是否成功
            return new BufferedReader(new InputStreamReader(inputStream,charset)).lines()
                    .map(function).anyMatch(item -> item);
        }
    }
}
